import React, { Component } from 'react';
import {Table, Form, Tabs, Icon } from 'antd';
import message from '@wanhu/antd-legacy/lib/message'
import api from '../../../api/api';
import './RiskAssessmentReport.less'
import { canvasToPdf, getA4px ,getMm2px} from '../../../../src/utils'
import html2canvas from 'html2canvas';
import jsPDF from '../../../../src/jspdf'

const TabPane = Tabs.TabPane;


// BMI:BMI,waistline:腰围,BP:血压,BG:血糖,dietaryHabit:饮食习惯,drink:饮酒,exercise:运动,HBALC:糖化血红蛋白,HDL:高密度脂蛋白胆固醇HDL-C,LDL:低密度脂蛋白胆固醇,sleepTime:睡眠时长,smoke:吸烟,TCHO:总胆固醇,TG:甘油三脂,vegetableFruit:是否经常食用新鲜蔬菜和水果
const habits = ['dietaryHabit','drink','exercise','sleepTime','smoke','vegetableFruit']

const targetTimeTip = {
  'BMI':'有效期:6个月',
  'waistline':'有效期:6个月',
  'BP':'有效期:1个月',
  'BG':'有效期:1个月',
  'HBALC':'有效期:3个月',
  'TCHO':'有效期:3个月',
  'HDL':'有效期:3个月',
  'LDL':'有效期:3个月',
  'TG':'有效期:3个月',
}
class RiskAssessmentReport extends Component {
  constructor(props){
    super(props)
    this.state={
        riskColumns : [{
          title: '预测时长',
          dataIndex: 'riskPeriodName',
          key: 'riskPeriodName',
        }, {
          title: '风险指标',
          dataIndex: 'riskName',
          key: 'riskName',
          render:(val)=>{
            return val
          }
        }, {
          title: '风险值（概率）',
          dataIndex: 'valueNum',
          key: 'valueNum',
          render:(val)=>{
            return this.formatPercent(val)
          }
        },{
          title: '风险排名',
          dataIndex: 'rnk',
          key: 'rnk',
          render:(val)=>{
            return this.formatPercent(val)
          }
        }],
        report:{

        },
        loading:false
    }
  }

  componentDidMount() {
    this.init();
  }



  async init() {
    try {
      // 测试数据
      // let report = {"healthGuides":[{"datas":["每日至少吃五份新鲜蔬菜和水果，总量达到八两到一斤，其中深色蔬菜要占据蔬菜的一半以上；","使用天然香草或香辛料取代过多的盐分，食盐应限制在每日< 6克(啤酒瓶盖平平一盖的量)；","避免高胆固醇及饱和脂肪食物的摄取，像是内脏类、卵、海鲜类的头部、精致糕点等，用禽肉类或水产品代替畜肉类；","烹调宜多采取炖、卤、清蒸、凉拌、烧、烤等方式，以减少油脂摄取，每日限油25克；","以大豆油、花生油、玉米油、橄榄油、葵花籽油、亚麻籽油等植物油替代猪油、羊油、牛油等动物油；"],"typeName":"均衡饮食","type":"A"},{"datas":["戒烟是一个长期的过程，首先需要有戒烟的意识，然后循序渐进的戒，每天少抽一根或每周少抽两根；","丢弃所有的烟草、烟灰缸、火柴、打火机，避免一见到这些就“条件反射”地想要吸烟；","烟瘾来时，做深呼吸活动或咀嚼无糖口香糖，尽量不要用零食代替烟草以免引起血糖升高，导致身体过胖等不良现象的发生；","用餐后喝水、吃水果或散步来代替饭后一支烟的习惯；","安排一些体育活动，如游泳、跑步、钓鱼、打球等，一方面可以缓解压力和精神紧张，一方面还有助于把注意力从吸烟上引开；","请家人监督，并对戒烟的成就给予鼓励或奖励；","有戒烟意愿但经尝试后仍未能戒断的吸烟者，可向医生咨询，采用尼古丁替代疗法和/或伐尼克兰等处方药来协助戒烟。"],"typeName":"戒烟管理","type":"B"},{"datas":["原则上不建议饮酒，如饮酒，建议少量，男性饮酒者的葡萄酒≤100 ml(相当于2两)/ 天，或啤酒≤ 250 ml(半瓶)/天，或白酒≤ 50 ml(1两)/天；女性减半；","不饮高度烈性酒，高度酒是指酒精度在41%vol以上的酒；","血压在150/90以上、患有糖尿病、胰脏炎、血脂异常或神经病变者，应绝对禁酒；"],"typeName":"限酒管理","type":"C"},{"datas":["每周3~5次，每次30~50 分钟的规律性运动，强度达到中等，如快步走，步数至少达到6000步或达到微微出汗的程度；","运动过程中若发生胸痛、喘鸣、脸部潮红时，应立即停止运动，坐下休息片刻。若症状仍无改善，应立即到医院就诊；","有意识开展部分上肢拉力及全身柔韧度锻炼（如八段锦，太极拳，彩带龙），以增强肌肉力量和餐后的热量消耗。","大气污染严重时，避免外出和锻炼；","每次静坐时间不超过90分钟；","针对肩、颈、腰、背这些关键部位的肌肉进行拉伸和转体活动（可借助瑜伽垫、哑铃、弹力带等健身工具），每组拉伸时间大概20-30秒，进行2-4组；","结合练习臀桥锻炼、小燕飞、仰卧起坐等动作；","适宜强度为运动后感觉轻度呼吸急促，周身微热，面色微红，内心感觉轻松愉快。虽然稍微感觉有点疲乏，但经过休息后可以消除，并且没有明显疼痛和麻木；"],"typeName":"规律运动","type":"D"},{"datas":["每日饮水量达到5杯以上（大概1500ml-2000ml）；","以白开水代替饮料；","水温宜在35-40℃；"],"typeName":"饮水管理","type":"H"}],"riskLevel":"低风险","city":"北京市","majorDiseasesHospitalizationRisk":[{"riskName":"重大疾病住院1次概率预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0.08","risk":"ip_cnt1_ci","value":"8%","rnk":"0.2790004384042087"},{"riskName":"重大疾病住院2次概率预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0","risk":"ip_cnt2_ci","value":"0%","rnk":"0.2790004384042087"},{"riskName":"重大疾病住院3次概率预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0","risk":"ip_cnt3_ci","value":"0%","rnk":"0.2790004384042087"},{"riskName":"重大疾病住院总支出预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0.08","risk":"ip_cost_ci","value":"0.08","rnk":"0.2790004384042087"},{"riskName":"重大疾病住院1次概率预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.21","risk":"ip_cnt1_ci","value":"21%","rnk":"0.27312582200789126"},{"riskName":"重大疾病住院2次概率预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.03","risk":"ip_cnt2_ci","value":"3%","rnk":"0.27312582200789126"},{"riskName":"重大疾病住院3次概率预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.03","risk":"ip_cnt3_ci","value":"3%","rnk":"0.27312582200789126"},{"riskName":"重大疾病住院总支出预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.06","risk":"ip_cost_ci","value":"0.06","rnk":"0.27312582200789126"},{"riskName":"重大疾病住院1次概率预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.3","risk":"ip_cnt1_ci","value":"30%","rnk":"0.2721613327487944"},{"riskName":"重大疾病住院2次概率预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.05","risk":"ip_cnt2_ci","value":"5%","rnk":"0.2721613327487944"},{"riskName":"重大疾病住院3次概率预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.05","risk":"ip_cnt3_ci","value":"5%","rnk":"0.2721613327487944"},{"riskName":"重大疾病住院总支出预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.8","risk":"ip_cost_ci","value":"0.8","rnk":"0.2721613327487944"}],"sex":1,"hospitalizationRisk":[{"riskName":"住院1次概率预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0.03","risk":"ip_cnt1","value":"3%","rnk":"0.12012275317843052"},{"riskName":"住院2次概率预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0.03","risk":"ip_cnt2","value":"3%","rnk":"0.12012275317843052"},{"riskName":"住院3次概率预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0.03","risk":"ip_cnt3","value":"3%","rnk":"0.12012275317843052"},{"riskName":"住院总支出预测","riskPeriod":"1yr","riskPeriodName":"未来1年","valueNum":"0.09","risk":"ip_cost","value":"0.09","rnk":"0.12012275317843052"},{"riskName":"住院1次概率预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.02","risk":"ip_cnt1","value":"2%","rnk":"0.11538798772468216"},{"riskName":"住院2次概率预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.02","risk":"ip_cnt2","value":"2%","rnk":"0.11538798772468216"},{"riskName":"住院3次概率预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.02","risk":"ip_cnt3","value":"2%","rnk":"0.11538798772468216"},{"riskName":"住院总支出预测","riskPeriod":"3yr","riskPeriodName":"未来3年","valueNum":"0.06","risk":"ip_cost","value":"0.06","rnk":"0.11538798772468216"},{"riskName":"住院1次概率预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.04","risk":"ip_cnt1","value":"4%","rnk":"0.10854888206926787"},{"riskName":"住院2次概率预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.04","risk":"ip_cnt2","value":"4%","rnk":"0.10854888206926787"},{"riskName":"住院3次概率预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.04","risk":"ip_cnt3","value":"4%","rnk":"0.10854888206926787"},{"riskName":"住院总支出预测","riskPeriod":"5yr","riskPeriodName":"未来5年","valueNum":"0.12","risk":"ip_cost","value":"0.12","rnk":"0.10854888206926787"}],"diseases":["高血压"],"cancerRisk":[{"riskName":"肺恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00096","riskPeriodName":"未来5年","risk":"C34.9","value":"0.1%","rnk":"0.2348969750109601"},{"riskName":"肝恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00604","riskPeriodName":"未来5年","risk":"C22.9","value":"0.6%","rnk":"0.42569048662867165"},{"riskName":"胃恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00488","riskPeriodName":"未来5年","risk":"C16","value":"0.49%","rnk":"0.3972818939061815"},{"riskName":"食管恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00045","riskPeriodName":"未来5年","risk":"C15","value":"0.45%","rnk":"0.4915387987724682"},{"riskName":"结肠恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00039","riskPeriodName":"未来5年","risk":"C18","value":"0.04%","rnk":"0.005436212187637002"},{"riskName":"直肠恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00099","riskPeriodName":"未来5年","risk":"C20","value":"0.1%","rnk":"0.005436212187637002"},{"riskName":"乳腺恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00027","riskPeriodName":"未来5年","risk":"C50","value":"0.0%","rnk":"0.4881192459447611"},{"riskName":"宫颈恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00028","riskPeriodName":"未来5年","risk":"C53","value":"0.0%","rnk":"0.5792196405085489"},{"riskName":"前列腺恶性肿瘤发生率预测","riskPeriod":"5yr","valueNum":"0.00338","riskPeriodName":"未来5年","risk":"C61","value":"0.34%","rnk":"0.38439281017097765"}],"percent":"0.35006","chronicDiseaseRisks":["饮酒:长期嗜酒","蔬菜水果摄入:偶尔"],"longRisk":[{"riskName":"重大心脑血管疾病风险","riskPeriod":"5yr","valueNum":"0.3","riskPeriodName":"未来5年","risk":"major_cvd","value":"30%","rnk":"0.4522941781141949"},{"riskName":"糖尿病肾病风险","riskPeriod":"5yr","valueNum":"0.00002","riskPeriodName":"未来5年","risk":"chr_kidney","value":"0%","rnk":"0.4522941781141949"}],"healthManagementTarget":[{"result":0,"indectorName":"BMI","targetDesc":"18.5-23.9","value":"20.52","indectorCode":"BMI"},{"result":0,"indectorName":"腰围","targetDesc":"<90","value":"70","indectorCode":"waistline"},{"result":0,"indectorName":"血压","targetDesc":"130/80mmHg以下","value":"120/75mmHg","indectorCode":"BP"},{"result":null,"indectorName":"血糖","targetDesc":"空腹:3.9-6.1,餐后2h:<7.8","value":null,"indectorCode":"BG"},{"result":null,"indectorName":"糖化血红蛋白","targetDesc":"<6","value":null,"indectorCode":"HBALC"},{"result":null,"indectorName":"高密度脂蛋白胆固醇HDL-C","targetDesc":">1.0","value":null,"indectorCode":"HDL"},{"result":null,"indectorName":"低密度脂蛋白胆固醇","targetDesc":"<3.4","value":null,"indectorCode":"LDL"},{"result":null,"indectorName":"总胆固醇","targetDesc":"<5.2","value":null,"indectorCode":"TCHO"},{"result":null,"indectorName":"甘油三脂","targetDesc":"<1.7","value":null,"indectorCode":"TG"},{"result":1,"indectorName":"抽烟情况","targetDesc":"戒烟","value":"是的,每天1.50包","indectorCode":"smoke"},{"result":1,"indectorName":"饮酒情况","targetDesc":"白酒不超过一两，红酒不超过100ml，啤酒不超过250ml","value":"经常，中量","indectorCode":"drink"},{"result":-1,"indectorName":"新鲜蔬菜水果摄入","targetDesc":"新鲜蔬菜摄入每天至少六两,水果摄入每天至少四两","value":"偶尔","indectorCode":"vegetableFruit"},{"result":1,"indectorName":"饮食口味","targetDesc":"均衡清淡：有蛋有奶有荤有素有粗有细，口味适中","value":"偏咸，偏油","indectorCode":"dietaryHabit"},{"result":-1,"indectorName":"运动","targetDesc":"中等强度有氧运动≥30分钟，步数＞6000步","value":"几乎从不","indectorCode":"exercise"},{"result":0,"indectorName":"睡眠","targetDesc":"7-8小时","value":"7-8个小时","indectorCode":"sleepTime"}],"reportDate":"2021-07-06","shortRisk":[{"riskName":"脑卒中风险","riskPeriod":"1yr","valueNum":"0.00561","riskPeriodName":"未来1年","risk":"stroke","value":"0.06%","rnk":"0.053485313459009205"},{"riskName":"冠心病风险","riskPeriod":"1yr","valueNum":"0.02","riskPeriodName":"未来1年","risk":"chd","value":"2%","rnk":"0.8362121876370013"},{"riskName":"糖尿病肾病风险","riskPeriod":"1yr","valueNum":"0.24321","riskPeriodName":"未来1年","risk":"chr_kidney","value":"24.32%","rnk":"0.8362121876370013"}],"name":"姜平基","healthyAssets":[{"metric":"饮酒","level":"high","value":"长期嗜酒"},{"metric":"吸烟情况","level":"low","value":"从不吸烟"},{"metric":"运动情况","level":"low","value":"经常"}],"examineAdvices":["血压","血糖（空腹血糖、餐后）","血脂","尿微量白蛋白","肾功能","眼底检查（眼底检查、眼底镜）","心电图","B超检查（肝胆B超、肾脏B超、胰腺B超）","甲胎蛋白（AFP）","粪便隐血","CT检查（胸部CT、脑CT）","糖耐量试验","肝功能"],"id":"60e3cf2868c13709a8d18f73","age":66}
      let report = await api.getAssessmentReportDetail(this.props.match.params.reportId)
      // 健康管理目标字段，拆分成2个，目标+生活习惯
      report.healthManagementTarget_target = report.healthManagementTarget.filter(item=>{
        return !habits.includes(item.indectorCode)
      })
      report.healthManagementTarget_habit = report.healthManagementTarget.filter(item=>{
        return habits.includes(item.indectorCode)
      })
      this.setState({
          report
      })
    } catch (e) {
    message.error(e.message);
    } finally {
    this.setState({ initing: false });
    }
  }

  // 根据生日转换年龄
  /* eslint-disable class-methods-use-this */
  getAgeByBirthday = (dateString)=> {
    if (!dateString) return '';
    const today = new Date();
    const birthDate = new Date(dateString);
    const age = today.getFullYear() - birthDate.getFullYear();
    return age;
  }

  // 短期风险
  renderShortRisk=()=>{
    let dataSource = this.state.report.shortRisk || []
    dataSource.forEach((item,index)=>{
      return item.key = String(index)
    })
    return (
      dataSource.length > 0 ? (
        <TabPane tab="短期风险" key="1">
          <div className="i-risk">
            <Table dataSource={dataSource} columns={ this.state.riskColumns } pagination={false}></Table>
            <div className="tip">
              <div className="t-title">说明：</div>
              <div className="t-des">
                {
                  dataSource.map((item,index)=>{
                    return <div key={index}>{item.riskPeriodName}罹患{item.riskName}：{ this.formatPercent(item.valueNum)}，高于{ item.rnk == '0' ? '所有' : this.formatPercent(1 - item.rnk)}的人群。</div>
                  })
                }
              </div>
            </div>
          </div>
      </TabPane>
      ) : ''
    )
  }


  // 短期风险print
  renderShortRiskPrint = ()=>{
    let dataSource = this.state.report.shortRisk || []
    dataSource.forEach((item,index)=>{
      return item.key = String(index)
    })
    return (
      dataSource.length > 0 ? (
        <div className="t-des">
          {
            dataSource.map((item,index)=>{
              return <div key={index}>{item.riskPeriodName}罹患{item.riskName}：{ this.formatPercent(item.valueNum)}，高于{ item.rnk == '0' ? '所有' : this.formatPercent(1 - item.rnk)}的人群。</div>
            })
          }
        </div>
      ) : ''
    )
  }

  // 长期风险
  renderLongRisk=()=>{
    let dataSource =  this.state.report.longRisk || []
    dataSource.forEach((item,index)=>{
      return item.key = String(index)
    })
    return (
      dataSource.length > 0 ? (
      <TabPane tab="长期风险" key="2">
        <div className="i-risk">
          <Table dataSource={dataSource} columns={ this.state.riskColumns } pagination={false}></Table>
          <div className="tip">
            <div className="t-title">说明：</div>
            <div className="t-des">
              {
                dataSource.map((item,index)=>{
                  return <div key={index}>{item.riskPeriodName}罹患{item.riskName}：{ this.formatPercent(item.valueNum)}，高于{item.rnk == '0' ? '所有' :  this.formatPercent(1 - item.rnk)}的人群。</div>
                })
              }
            </div>
          </div>
        </div>
      </TabPane>
      ) : ''
    )
  }

  renderLongRiskPrint(){
    let dataSource =  this.state.report.longRisk || []
    dataSource.forEach((item,index)=>{
      return item.key = String(index)
    })
    return (
      dataSource.length > 0 ? (
        <div className="t-des">
          {
            dataSource.map((item,index)=>{
              return <div key={index}>{item.riskPeriodName}罹患{item.riskName}：{ this.formatPercent(item.valueNum)}，高于{item.rnk == '0' ? '所有' :  this.formatPercent(1 - item.rnk)}的人群。</div>
            })
          }
        </div>
      ) : ''
    )
  }

  // 恶性肿瘤风险
  renderCancerRisk=()=>{
    let dataSource = this.state.report.cancerRisk || []
    dataSource.forEach((item,index)=>{
      return item.key = String(index)
    })
    return (
      dataSource.length > 0 ? (
        <TabPane tab="恶性肿瘤风险" key="3">
          <div className="i-risk">
            <Table dataSource={dataSource} columns={ this.state.riskColumns } pagination={false}></Table>
            <div className="tip">
              <div className="t-title">说明：</div>
              <div className="t-des">
                {
                  dataSource.map((item,index)=>{
                    return <div key={index}>{item.riskPeriodName}罹患{item.riskName}：{this.formatPercent(item.valueNum)}，高于{ item.rnk == '0' ? '所有' :  this.formatPercent(1 - item.rnk)}的人群。</div>
                  })
                }
              </div>
            </div>
          </div>
        </TabPane>
      ) : ''
    )
  }

  renderCancerRiskPrint=()=>{
    let dataSource = this.state.report.cancerRisk || []
    dataSource.forEach((item,index)=>{
      return item.key = String(index)
    })
    return (
      dataSource.length > 0 ? (
        <div className="t-des">
          {
            dataSource.map((item,index)=>{
              return (<div key={index}>
                {item.riskPeriodName}罹患{item.riskName}：{this.formatPercent(item.valueNum)}，高于{ item.rnk == '0' ? '所有' :  this.formatPercent(1 - item.rnk)}的人群。<span style={{ padding:"0px 7px",color:"white",background: item.riskLevel ? "#FF8C00":"#169F85",fontSize:"20px",borderRadius:'4px',height:'30px',lineHeight:'31px',display:'inline-block'}}>{ item.riskLevel ? '高危风险' : '低危风险'}</span></div>
                )
            })
          }
        </div>
      ) : ''
    )
  }

  formatData = (item,data,key)=>{
    data.key = key
    data.risk = item.risk
    data.riskName = item.riskName
    if(item.riskPeriod === '1yr'){
      data.value1 = item.valueNum
      data.rnk1 = item.rnk

    }else if(item.riskPeriod === '3yr'){
      data.value3 = item.valueNum
      data.rnk3 = item.rnk
    }else if(item.riskPeriod === '5yr'){
      data.value5 = item.valueNum
      data.rnk5 = item.rnk
    }
  }


  // 住院风险
  renderHispitalRisk=()=>{

    const columns = [{
      title: '风险指标',
      dataIndex: 'riskName',
      key: 'riskName',
    }, {
      title: '未来一年',
      children:[
        {
          title: '预测结果',
          dataIndex: 'value1',
          key: 'value1',
          render:(val,record)=>{
            if(record.risk === 'ip_cost'){
              return Number(val).toFixed(2)+'(元)'
            }else{
              return this.formatPercent(val)
            }
          }
        },
        {
          title: '结果排名',
          dataIndex: 'rnk1',
          key: 'rnk1',
          render:(val)=>{
            return this.formatPercent(val)
          }
        },

      ]
    },
    {
      title: '未来3年',
      children:[
        {
          title: '预测结果',
          dataIndex: 'value3',
          key: 'value3',
          render:(val,record)=>{
            if(record.risk === 'ip_cost'){
              return Number(val).toFixed(2)+'(元)'
            }else{
              return this.formatPercent(val)
            }
          }
        },
        {
          title: '结果排名',
          dataIndex: 'rnk3',
          key: 'rnk3',
          render:(val)=>{
            return this.formatPercent(val)
          }
        }
      ]
    },
    {
      title: '未来5年',
      children:[
        {
          title: '预测结果',
          dataIndex: 'value5',
          key: 'value5',
          render:(val,record)=>{
            if(record.risk === 'ip_cost'){
              return Number(val).toFixed(2)+'(元)'
            }else{
              return this.formatPercent(val)
            }
          }
        },
        {
          title: '结果排名',
          dataIndex: 'rnk5',
          key: 'rnk5',
          render:(val)=>{
            return this.formatPercent(val)
          }
        }
      ]
    },
    ];
    let dataSourceArr = this.state.report.hospitalizationRisk || []
    // 将接口返回的数据转换成自己需要的格式
    let dataSourceTarget = []
    let dataSource1 = {}
    let dataSource3 = {}
    let dataSource5 = {}
    let dataSourceTotal = {}
    for(let item of dataSourceArr){
      // 总支出

      // 支出预测
      let temp= {}
      temp.riskName = item.riskName

      if(item.risk === 'ip_cost'){
        // 住院总支出预测
        this.formatData(item,dataSourceTotal,'dataSourceTotal')

      }else if(item.risk === 'ip_cnt1'){
        // 住院一次

        this.formatData(item,dataSource1,'dataSource1')

      }else if(item.risk === 'ip_cnt2'){
        // 住院3次

        this.formatData(item,dataSource3,'dataSource3')
      }else if(item.risk === 'ip_cnt3'){
        // 住院3次
        this.formatData(item,dataSource5,'dataSource5')
      }
    }
    dataSourceTarget.push(dataSource1,dataSource3,dataSource5,dataSourceTotal)


    return (
      dataSourceArr.length > 0 ? (
        <TabPane tab="住院风险" key="4">
          <div className="i-risk">
            <Table dataSource={dataSourceTarget} columns={ columns } pagination={false} bordered={true}></Table>
          </div>
        </TabPane>
      ) : ''
    )
  }

  // 重大疾病住院风险
  badDiseaseRisk=()=>{
    let dataSourceArr = this.state.report.majorDiseasesHospitalizationRisk || []
    const columns = [{
      title: '风险指标',
      dataIndex: 'riskName',
      key: 'riskName',
    }, {
      title: '未来一年',
      children:[
        {
          title: '预测结果',
          dataIndex: 'value1',
          key: 'value1',
          render:(val,record)=>{
            if(record.risk === 'ip_cost_ci'){
              return Number(val).toFixed(2)+'(元)'
            }else{
              return this.formatPercent(val)
            }
          }
        },
        {
          title: '结果排名',
          dataIndex: 'rnk1',
          key: 'rnk1',
          render:(val)=>{
            return this.formatPercent(val)
          }
        }
      ]
    },
    {
      title: '未来3年',
      children:[
        {
          title: '预测结果',
          dataIndex: 'value3',
          key: 'value3',
          render:(val,record)=>{
            if(record.risk === 'ip_cost_ci'){
              return Number(val).toFixed(2)+'(元)'
            }else{
              return this.formatPercent(val)
            }
          }
        },
        {
          title: '结果排名',
          dataIndex: 'rnk3',
          key: 'rnk3',
          render:(val)=>{
            return this.formatPercent(val)
          }
        }
      ]
    },
    {
      title: '未来5年',
      children:[
        {
          title: '预测结果',
          dataIndex: 'value5',
          key: 'value5',
          render:(val,record)=>{
            if(record.risk === 'ip_cost_ci'){
              return Number(val).toFixed(2)+'(元)'
            }else{
              return this.formatPercent(val)
            }
          }

        },
        {
          title: '结果排名',
          dataIndex: 'rnk5',
          key: 'rnk5',
          render:(val)=>{
            return this.formatPercent(val)
          }
        }
      ]
    },
    ];
    // 将接口返回的数据转换成自己需要的格式
    let dataSourceTarget = []
    // 总支出
    let dataSource1 = {}
    let dataSource2 = {}
    let dataSource3 = {}
    let dataSourceTotal = {}

    for(let item of dataSourceArr){

      if(item.risk === 'ip_cost_ci'){
        // 住院总支出预测
        this.formatData(item,dataSourceTotal,'dataSourceTotal')
      }else if(item.risk === 'ip_cnt1_ci'){
        // 住院一次
        this.formatData(item,dataSource1,'dataSource1')

      }else if(item.risk === 'ip_cnt2_ci'){
        // 住院2次
        this.formatData(item,dataSource2,'dataSource2')
      }else if(item.risk === 'ip_cnt3_ci'){
        // 住院3次
        this.formatData(item,dataSource3,'dataSource3')
      }

    }
    dataSourceTarget.push( dataSource1,dataSource2,dataSource3,dataSourceTotal)

    return (
      dataSourceArr.length > 0 ? (
        <TabPane tab="重大疾病住院风险" key="5">
          <div className="i-risk">
            <Table dataSource={dataSourceTarget} columns={ columns } pagination={false} bordered={true}></Table>
          </div>
        </TabPane>
      ) : ''
    )
  }
  // 获取健康指标单位
  getUnit = (key)=>{
    let unitObj={
      'BMI':'',
      'waistline':'cm',
      'BP':'',
      'BG':'mmol/L',
      'HBALC':'%',
      'TCHO':'mmol/L',
      'TG':'',
      'HDL':'',
      'LDL':''
    }
    return unitObj[key]
  }

  getTargetTitle = (indectorCode)=>{
    return targetTimeTip[indectorCode]
  }


  // 健康管理目标
  renderHealthIdeal = ()=>{
    let dataSource_target = this.state.report.healthManagementTarget_target || []
    let dataSource_hibit = this.state.report.healthManagementTarget_habit || []
    dataSource_target && dataSource_target.forEach((item,index)=>{
      return item.key = String(index)
    })
    dataSource_hibit && dataSource_hibit.forEach((item,index)=>{
      return item.key = String(index)
    })
    const columns = [
      {
        title: '监测指标',
        dataIndex: 'indectorName',
        key: 'indectorName',
        width:360,
        render:(val,row)=>{
          let unit = this.getUnit(row.indectorCode) || ''
          return val+ unit
        }
      },{
        title: '管理目标',
        dataIndex: 'targetDesc',
        key: 'targetDesc',
      },{
        title: '管理现状',
        dataIndex: 'value',
        key: 'value',
        width:360,
        render:(val,row)=>{

          return (
            <div>
              {/* bmi 需要保留小数位后2位 */}
              <span className="hd-num" title={ this.getTargetTitle(row.indectorCode)}>{val ? (row.indectorCode.toUpperCase()==='BMI' ? Number(val).toFixed(2) : val) : '-'}</span>
              <span className="hd-icon">
                {
                  row.result === null ? '' : (row.result === 0 ? <Icon type="like-o" /> : <Icon type="dislike-o" style={{color:"f00"}}/>)
                }
              </span>
            </div>
          )
        }
      }
    ]

    let hibitColumns = [
      {
        title: '生活习惯',
        dataIndex: 'indectorName',
        key: 'indectorName',
        width:360
      },{
        title: '',
        dataIndex: 'targetDesc',
        key: 'targetDesc',

      },{
        title: '',
        dataIndex: 'value',
        key: 'value',
        width:360,
        render:(val,row)=>{

          return (
            <div>
              <span className="hd-num">{val ? val : '-'}</span>
              <span className="hd-icon">
                {
                  row.result === null ? '' : (row.result === 0 ? <Icon type="like-o" /> : <Icon type="dislike-o" style={{color:"f00"}}/>)
                }
              </span>
            </div>
          )
        }
      }
    ]
    return (
      <div>
        <Table pagination={false} dataSource={dataSource_target} columns={ columns } bordered={true}></Table>
        <Table pagination={false} dataSource={dataSource_hibit} columns={ hibitColumns } bordered={true}></Table>
      </div>
    )

  }


  renderHealthIdealPrint = ()=>{
    let dataSource_target = this.state.report.healthManagementTarget_target || []
    let dataSource_hibit = this.state.report.healthManagementTarget_habit || []
    dataSource_target && dataSource_target.forEach((item,index)=>{
      return item.key = String(index)
    })
    dataSource_hibit && dataSource_hibit.forEach((item,index)=>{
      return item.key = String(index)
    })

    dataSource_target = dataSource_target.filter(item=>{
      return item.result
    })

    dataSource_hibit = dataSource_hibit.filter(item=>{
      return item.result
    })
    const columns = [
      {
        title: '监测指标',
        dataIndex: 'indectorName',
        key: 'indectorName',
        width:360,
        render:(val,row)=>{
          let unit = this.getUnit(row.indectorCode) || ''
          return val+ unit
        }
      },{
        title: '管理目标',
        dataIndex: 'targetDesc',
        key: 'targetDesc',
      },{
        title: '管理现状',
        dataIndex: 'value',
        key: 'value',
        width:360,
        render:(val,row)=>{

          return (
            <div>
              {/* bmi 需要保留小数位后2位 */}
              {
                row.result ? (
                  <div>
                    <span className="hd-num" title={ this.getTargetTitle(row.indectorCode)}>{val ? (row.indectorCode.toUpperCase()==='BMI' ? Number(val).toFixed(2) : val) : '-'}</span>
                    <span className="hd-icon">
                        <Icon type="dislike-o" style={{color:"f00"}}/>
                    </span>
                  </div>
                ) : ''
              }

            </div>
          )
        }
      }
    ]

    let hibitColumns = [
      {
        title: '生活习惯',
        dataIndex: 'indectorName',
        key: 'indectorName',
        width:360
      },{
        title: '',
        dataIndex: 'targetDesc',
        key: 'targetDesc',
      },{
        title: '',
        dataIndex: 'value',
        key: 'value',
        width:360,
        render:(val,row)=>{

          return (
            <div>
              {
                row.result ? (
                  <div>
                    <span className="hd-num">{val ? val : '-'}</span>
                    <span className="hd-icon">
                      <Icon type="dislike-o" style={{color:"f00"}}/>
                    </span>
                  </div>
                ) : ''
              }
            </div>
          )
        }
      }
    ]
    return (
      <div>
        <div className="print-item">
          <Table  pagination={false} dataSource={dataSource_target} columns={ columns } bordered={true}></Table>
        </div>
        <div className="print-item">
          <Table pagination={false} dataSource={dataSource_hibit} columns={ hibitColumns } bordered={true}></Table>
        </div>
      </div>
    )

  }



  // 健康指导建议
  renderAdvise=()=>{
    let advise = this.state.report.healthGuides || []


    // 所有癌症的疾病都归为一类
    // 癌症的Icd10 如下
    /*
    let cancerIcd10 = ['C34','C22','C16','C15','C18','C19_20','C50','C53','C61']
    let cancerAdvise = {
      type:'cancer',
      typeName:'恶性肿瘤风险',
      datas:[]
    }
    advise = advise.filter(item=>{
      // 癌症
      if(cancerIcd10.includes(item.type)){
        cancerAdvise.datas = cancerAdvise.datas.concat(item.datas)
        return false
      }else{
        return true
      }
    })
    if(cancerAdvise.datas.length > 0){
      advise.unshift(cancerAdvise)
    }
    */



    // 对相同类型的建议进行合并
    let comAdvise = {}
    for(let item of advise){
      if(comAdvise[item.type]){
        comAdvise[item.type]['datas'] = comAdvise[item.type]['datas'].concat(item.datas)
      }else{
        comAdvise[item.type] = {
          type:item.type,
          typeName:item.typeName,
          datas:item.datas
        }
      }
    }
    let tempAdvise = []
    for(let key of Object.keys(comAdvise)){
      tempAdvise.push(comAdvise[key])
    }


    return (
    <Tabs defaultActiveKey="1">
      {
        tempAdvise.map((item,index)=>{
          return <TabPane tab={item.typeName} key={item.typeName}>{item.datas.map((item,index2)=>{
            return <p key={index2}>{item}</p>
          })}</TabPane>
        })
      }
    </Tabs>
    )
  }

  renderPrintAdvise=()=>{
    let advise = this.state.report.healthGuides || []
    let comAdvise = {}
    for(let item of advise){
      if(comAdvise[item.type]){
        comAdvise[item.type]['datas'] = comAdvise[item.type]['datas'].concat(item.datas)
      }else{
        comAdvise[item.type] = {
          type:item.type,
          typeName:item.typeName,
          datas:item.datas
        }
      }
    }
    let tempAdvise = []
    for(let key of Object.keys(comAdvise)){
      tempAdvise.push(comAdvise[key])
    }
    return (
      <div className="a-innser">
        {
          tempAdvise.map((item,index)=>{
            return <div className="a-i-item print-item" key={'a'+index}>
              <div className="a-i-i-title">{item.typeName}</div>
              <div className="a-i-i-content">
                {
                  item.datas.map((d,dIndex)=>{

                    return <div key={'id'+dIndex}><code>{d}</code></div>
                  })
                }
              </div>
            </div>
          })
        }
      </div>
    )

  }


  formatPercent = (val)=>{
    // 只有不等于nan才能显示
    if(!Number.isNaN(val)){
      return (Math.round(Number(val) * 10000) / 100).toFixed(2)  + '%'
    }
  }
  // 千分位
  formatThousand = (val)=>{
    // 只有不等于nan才能显示
    if(!Number.isNaN(val)){
      return (Math.round(Number(val) * 100000) / 100).toFixed(2)  + '‰'
    }
  }


  goMember =()=>{
    // console.log('this.props.history:',this.props.history)
    // this.props.history.push('/customerCenter')
    this.props.history.goBack(-2)
  }
  goReport = ()=>{
    this.props.history.goBack()
  }


  exportPdf = ()=>{

    // 现有的
    // let target = document.getElementById('cont-print')
    // html2canvas(target).then(canvas=>{
    //   canvasToPdf(canvas)
    // })
    // 显示loading页
    this.setState({
      loading:true
    },function(){
      setTimeout(()=>{
        this.printPdf()
      })
    })
  }

  printPdf = ()=>{
    // 导出pdf
    let [a4Width_px,a4Height_px] = getA4px()
    let marginHeight_px = 10 //上下边距,如果没有上下边距，元素都会挤在一块
    let element1 = document.getElementById('cont-patient')
    let elementArr = Array.from(document.querySelectorAll('.print-item'))
    elementArr.unshift(element1)

    let element2CanvasPromiseArr = elementArr.map(item=>{
      return html2canvas(item)
    })

    Promise.all(element2CanvasPromiseArr).then(canvasArr=>{

      let pages = [] // [[a,b],[c]]
      let height = 0
      let pageElement = [] // 可以放在同一页的element元素
      // 这里需要将px转为mm
      let px2mm = 1 / getMm2px()
      let pdf = new jsPDF('', 'mm', 'a4');
      // let position = 0
      let a4Width_mm = 210-10  // 左右留5mm边距
      let a4Height_mm = 297  // 上下留边距
      let marginHeight_mm = marginHeight_px * px2mm
      let radio = a4Width_mm / (1120 * px2mm) // 1120为图片的宽度

      canvasArr.forEach((item,index)=>{
        let itemH = (item.height + marginHeight_px) * radio   // 实际高度加上margin的高度。因为图片画到canvas上有缩放，所以这里要乘以radio        // 加上该元素之后，高度大于a4的高度
        // console.log('itemH:',itemH)
        // console.log('height + itemH:',height + itemH)
        // console.log('a4Height_px:',a4Height_px)

        // a4Height_px 为a4纸的高，canvas画到canvas上的时候
        if(height + itemH > a4Height_px){
          // 满一页时放到数组里
          pages.push(pageElement)
          height = itemH
          pageElement = [item]
        }else {
          height += itemH
          pageElement.push(item)
        }
        //
        if(index === canvasArr.length-1){
          pages.push(pageElement)
        }
      })


      pages.forEach((canvasArr,pIndex)=>{
        let marginMm = 5   // 添加5mm上边距
        canvasArr.forEach((canvas,cIndex)=>{
          let pageData = canvas.toDataURL('image/jpeg', 1.0);
          let imgHeight = radio * (canvas.height * px2mm)  // 添加边距
          pdf.addImage(pageData,'JPEG', 5 , marginMm ,a4Width_mm,imgHeight)
          marginMm = marginMm +imgHeight + marginHeight_mm

        })
        if(pIndex < pages.length -1){
          pdf.addPage()
        }
        // position += a4Height_mm
      })

      pdf.save('风险评估报告.pdf');
      this.setState({
        loading:false
      })
    })
  }

  renderMainPage(){
    let { report } = this.state
    return (
    <div>
      <div className="cont" id="cont">
          <div className="patient">
            {/* <span className="name">{ report.name }</span>
            <span>{ report.age }</span>
            <span>{ report.city }</span>
            <span>{ report.sex ? '男' : '女' }</span> */}
            {/* 报告更新时间 */}
            <span className="p-time" style={{border:'none'}}>报告更新时间：{ report.reportDate}</span>
            <span style={{textDecoration:'underline',float:'right',color:'blue',cursor:'pointer'}}   onClick={this.exportPdf}>导出pdf</span>
          </div>
          <div className="report">
            <div className="risk">
              <span className="r-item r-item1">慢病风险等级 : <span className="danger">{ report.riskLevel }</span></span>
              <span className="r-item r-item2">综合风险排名 : <span className="danger">高于{this.formatPercent(1 - report.percent)}的评估人群</span></span>
            </div>
            <div className="detail reportItem">
              <div className="d-item bad">
                <div className="d-title">现有疾病</div>
                <div className="d-cont">
                  {
                    report.diseases && report.diseases.map((item,index)=>{
                      return <span key={index} className="d-c-item">{ item }</span>
                    })
                  }
                </div>
              </div>

              <div className="d-item bad">
                <div className="d-title">慢病风险因素</div>
                <div className="d-cont">
                  {
                    report.chronicDiseaseRisks && report.chronicDiseaseRisks.map((item,index)=>{
                      return <span key={index} className="d-c-item">{ item }</span>
                    })
                  }
                </div>
              </div>

              <div className="d-item bad">
                <div className="d-title">健康不良资产</div>
                <div className="d-cont">
                {
                    report.healthyAssets && report.healthyAssets.filter(item=>{return item.level === 'high'}).map((item,index)=>{
                      return (<div key={index} className="d-c-item">
                        <div>{ item.metric }</div>
                        <div>{ item.value }</div>
                      </div>)
                    })
                  }
                </div>
              </div>

              <div className="d-item good">
                <div className="d-title">健康优良资产</div>
                <div className="d-cont">
                  {
                    report.healthyAssets && report.healthyAssets.filter(item=>{return item.level === 'low'}).map((item,index)=>{
                      return (<div key={index} className="d-c-item">
                        <div>{ item.metric }</div>
                        <div>{ item.value }</div>
                      </div>)
                    })
                  }
                </div>
              </div>

            </div>

            {/* 风险指标 */}
            <div className="report-title">风险指标:</div>
            <div className="indicator reportItem">
              <Tabs defaultActiveKey="1">
                { this.renderShortRisk()}
                { this.renderLongRisk()}
                { this.renderCancerRisk() }
                { this.renderHispitalRisk() }
                { this.badDiseaseRisk() }
              </Tabs>
            </div>

            {/* 健康管理目标 */}
            <div className="report-title">健康管理目标</div>
            <div className="ideal reportItem">
              { this.renderHealthIdeal()}
              <div className="i-tip">管理现状中的“-”代表有限时间内，未采集相关指标值。</div>
            </div>

            {/* 健康指导建议 */}
            <div className="report-title">健康指导建议</div>
            <div className="advise reportItem">
              { this.renderAdvise()}
            </div>

            {/* 建议体检筛选项目 */}
            <div className="report-title">建议体检筛选项目:</div>
            <div className="physical reportItem">
              <div className="tip">根据您目前的各项身体指标特征及风险预测结果，建议做如下体检筛查项目：</div>
              {
                report.examineAdvices && report.examineAdvices.map((item,index)=>{
                  return <div className="p-item" key={index}>{item}</div>
                })
              }
            </div>
          </div>
        </div>

    </div>)
  }
  renderPrintPage(){
    let { report } = this.state
    return (
      <div>
        <div className="cont-print" id="cont-print">
          <div className="patient" id="cont-patient">
            <span className="name">{ report.name }</span>
            <span>{ report.age }岁</span>
            <span>{ report.city }</span>
            <span>{ report.sex ? '男' : '女' }性</span>

            <span className="p-time" style={{border:'none'}}>报告更新时间：{ report.reportDate}</span>
          </div>
          <div className="report" id="report">
            <div className="risk print-item">
              <span className="r-item r-item1">慢病风险等级 : <span className="r-item-result">{ report.riskLevel }</span></span>
              <span className="r-item r-item2">综合风险排名 : <span className="r-item-result">高于{this.formatPercent(1 - report.percent)}的评估人群</span></span>
            </div>
            <div className="detail reportItem print-item">

              <div className="d-item bad">
                <div className="d-title">健康不良资产</div>
                <div className="d-cont">
                {
                    report.healthyAssets && report.healthyAssets.filter(item=>{return item.level === 'high'}).map((item,index)=>{
                      return (<div key={index} className="d-c-item">
                        <span>{ item.metric}</span><br/>
                        <span>{ item.value}</span>
                      </div>)
                    }) || (<div className="d-c-item">
                      无
                    </div>)
                  }
                </div>
              </div>
              <div className="d-item good">
                <div className="d-title">健康优良资产</div>
                <div className="d-cont">
                  {
                    report.healthyAssets && report.healthyAssets.filter(item=>{return item.level === 'low'}).map((item,index)=>{
                      return (<div key={index} className="d-c-item">
                        <span>{ item.metric}</span><br/>
                        <span>{ item.value}</span>
                      </div>)
                    }) || <span className="d-c-item">无</span>
                  }
                </div>
              </div>

            </div>

            {/* 风险指标 */}

            <div className="report-title print-item">风险指标</div>
            <div className="indicator indicator-short print-item">
              <div className="i-title">短期风险</div>
              <div className="i-cont">
                { this.renderShortRiskPrint() || '无'}
              </div>
            </div>

            <div className="indicator indicator-long print-item">
              <div className="i-title">长期风险</div>
              <div className="i-cont">
                { this.renderLongRiskPrint() || '无'}
              </div>

            </div>

            <div className="indicator indicator-cancel print-item">
              <div className="i-title">恶性肿瘤风险</div>
              <div className="i-cont">
              { this.renderCancerRiskPrint() || '无'}
              </div>
            </div>

            {/* 健康管理目标 */}
            <div className="report-title print-item">健康管理目标1</div>
            <div className="ideal reportItem">
              { this.renderHealthIdealPrint()}
              <div className="i-tip print-item">管理现状中的“-”代表有限时间内，未采集相关指标值。</div>
            </div>

            {/* 健康指导建议 */}
            <div className="report-title advise-title print-item">健康指导建议</div>
            <div className="advise reportItem">
              { this.renderPrintAdvise()}
            </div>

            {/* 建议体检筛选项目 */}
            <div className="report-title print-item">建议体检筛选项目</div>
            <div className="physical reportItem print-item">
              <div className="tip">根据您目前的各项身体指标特征及风险预测结果，建议做如下体检筛查项目：</div>
              {
                report.examineAdvices && report.examineAdvices.map((item,index)=>{
                  return <div className="p-item" key={index}>{item}</div>
                })
              }
            </div>
          </div>
        </div>
      </div>
    )
  }
  renderLoading = ()=>{
    let { loading }  =  this.state
    return (
      loading ? (
      <div className="loading">
        导出中...
        {/* <Icon type="loading" /> */}
      </div>
      ) : ''
    )
  }
  render() {
    let { report } = this.state
    return (
      <div className="main">
        {
          this.renderLoading()
        }
        <div className="nav">
          <span className="nav-item" onClick={this.goMember}>会员管理</span>
          <span className="nav-line">/</span>
          <span className="nav-item" onClick={this.goReport}>风险评估报告记录</span>
          <span className="nav-line">/</span>
          <span className="nav-item">风险评估报告详情</span>
        </div>
        {
          this.renderMainPage()

        }
        <div style={{position:'absolute',top:'-9999px',left:'0'}}>
        {/* <div> */}
          {
            this.renderPrintPage()
          }
        </div>
      </div>
    )
  }
}
RiskAssessmentReport = Form.create({})(RiskAssessmentReport);
export default RiskAssessmentReport
